package com.qf.blogsystem.controller.website;

import com.alibaba.fastjson.JSON;
import com.qf.blogsystem.core.controller.BaseServlet;
import com.qf.blogsystem.core.utils.BaseConstants;
import com.qf.blogsystem.entity.DiscussPost;
import com.qf.blogsystem.entity.User;
import com.qf.blogsystem.service.CommentService;
import com.qf.blogsystem.service.DiscussPostService;
import com.qf.blogsystem.service.UserService;
import com.qf.blogsystem.service.impl.CommentServiceImpl;
import com.qf.blogsystem.service.impl.DiscussPostServiceImpl;
import com.qf.blogsystem.service.impl.UserServiceImpl;
import com.qf.blogsystem.vo.CommentVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/DiscussPostServlet/*")
public class DiscussPostServlet extends BaseServlet {
    /**
     * 创建帖子业务层实现对象
     */
    private DiscussPostService discussPostService = new DiscussPostServiceImpl();
    /**
     * 创建用户业务层实现对象
     */
    private UserService userService = new UserServiceImpl();
    /**
     * 创建帖子业务层实现对象
     */
    private CommentService commentService = new CommentServiceImpl();

    /**
     * 发布帖子
     * @return String
     * @throws Exception
     */
    public String publish() throws Exception {
        //获取登录用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return outJson(100, "登录超时，请先登录");
        }
        //接收前端传递的数据
        String json = request.getReader().readLine();
        DiscussPost discussPost = JSON.parseObject(json, DiscussPost.class);
        //封装用户
        discussPost.setUserId(loginUser.getId());
        boolean result = discussPostService.save(discussPost);
        if (result){
            return outJson(200,"发布成功!");
        }else {
            return BaseConstants.BASE_SCRIPT + ":发布失败!";
        }
    }

    /**
     * 查看帖子详情
     * @throws Exception
     */
    public void showDetails() throws Exception {
        //获取帖子id
        String id = request.getParameter("id");
        //查询帖子
        DiscussPost discussPost = discussPostService.byId(Integer.parseInt(id));
        //查询作者
        Integer userId = discussPost.getUserId();
        User user = userService.byId(userId);
        //查询帖子的评论
        List<CommentVo> commentVoList = commentService.commentListByEntityId(0,discussPost.getId());
        //把帖子的数据和作者的数据放到map中
        Map<String, Object> map = new HashMap();
        map.put("topic", discussPost);
        map.put("user", user);
        map.put("commentVoList", commentVoList);
        //跳转到视图
        outView("view/site/discuss-detail", map);
    }
}
